import BaseDTO from './BaseDTO.js';

/**
 * ProductDTO - 产品数据传输对象
 * 处理产品相关的数据验证、转换和格式化
 */
class ProductDTO extends BaseDTO {
    constructor(data = {}) {
        super(data);
        this.initializeRules();
    }

    /**
     * 初始化产品验证规则
     */
    initializeRules() {
        // 产品创建验证规则
        this.createRules = {
            name: {
                required: true,
                type: 'string',
                minLength: 2,
                maxLength: 200
            },
            description: {
                required: false,
                type: 'string',
                maxLength: 2000
            },
            price: {
                required: true,
                type: 'number',
                min: 0,
                custom: (value) => {
                    if (value !== undefined && value !== null) {
                        const decimalPlaces = (value.toString().split('.')[1] || '').length;
                        if (decimalPlaces > 2) {
                            return 'Price cannot have more than 2 decimal places';
                        }
                    }
                    return true;
                }
            },
            category: {
                required: true,
                type: 'string',
                minLength: 2,
                maxLength: 100
            },
            brand: {
                required: false,
                type: 'string',
                maxLength: 100
            },
            sku: {
                required: false,
                type: 'string',
                maxLength: 50,
                pattern: /^[A-Z0-9-_]+$/
            },
            stock_quantity: {
                required: true,
                type: 'integer',
                min: 0
            },
            weight: {
                required: false,
                type: 'number',
                min: 0
            },
            dimensions: {
                required: false,
                type: 'object',
                custom: (value) => {
                    if (value && typeof value === 'object') {
                        const requiredFields = ['length', 'width', 'height'];
                        for (const field of requiredFields) {
                            if (value[field] !== undefined && (typeof value[field] !== 'number' || value[field] < 0)) {
                                return `Dimension ${field} must be a positive number`;
                            }
                        }
                    }
                    return true;
                }
            },
            tags: {
                required: false,
                type: 'array',
                custom: (value) => {
                    if (value && Array.isArray(value)) {
                        for (const tag of value) {
                            if (typeof tag !== 'string' || tag.length > 50) {
                                return 'Each tag must be a string with maximum 50 characters';
                            }
                        }
                    }
                    return true;
                }
            },
            images: {
                required: false,
                type: 'array',
                custom: (value) => {
                    if (value && Array.isArray(value)) {
                        for (const image of value) {
                            if (typeof image !== 'string' || !this.isValidUrl(image)) {
                                return 'Each image must be a valid URL';
                            }
                        }
                    }
                    return true;
                }
            },
            status: {
                required: false,
                type: 'string',
                enum: ['active', 'inactive', 'discontinued', 'out_of_stock'],
                default: 'active'
            },
            is_featured: {
                required: false,
                type: 'boolean',
                default: false
            },
            discount_percentage: {
                required: false,
                type: 'number',
                min: 0,
                max: 100
            },
            meta_title: {
                required: false,
                type: 'string',
                maxLength: 60
            },
            meta_description: {
                required: false,
                type: 'string',
                maxLength: 160
            }
        };

        // 产品更新验证规则（所有字段都是可选的）
        this.updateRules = {
            name: {
                required: false,
                type: 'string',
                minLength: 2,
                maxLength: 200
            },
            description: {
                required: false,
                type: 'string',
                maxLength: 2000
            },
            price: {
                required: false,
                type: 'number',
                min: 0,
                custom: (value) => {
                    if (value !== undefined && value !== null) {
                        const decimalPlaces = (value.toString().split('.')[1] || '').length;
                        if (decimalPlaces > 2) {
                            return 'Price cannot have more than 2 decimal places';
                        }
                    }
                    return true;
                }
            },
            category: {
                required: false,
                type: 'string',
                minLength: 2,
                maxLength: 100
            },
            brand: {
                required: false,
                type: 'string',
                maxLength: 100
            },
            sku: {
                required: false,
                type: 'string',
                maxLength: 50,
                pattern: /^[A-Z0-9-_]+$/
            },
            stock_quantity: {
                required: false,
                type: 'integer',
                min: 0
            },
            weight: {
                required: false,
                type: 'number',
                min: 0
            },
            dimensions: {
                required: false,
                type: 'object',
                custom: (value) => {
                    if (value && typeof value === 'object') {
                        const requiredFields = ['length', 'width', 'height'];
                        for (const field of requiredFields) {
                            if (value[field] !== undefined && (typeof value[field] !== 'number' || value[field] < 0)) {
                                return `Dimension ${field} must be a positive number`;
                            }
                        }
                    }
                    return true;
                }
            },
            tags: {
                required: false,
                type: 'array',
                custom: (value) => {
                    if (value && Array.isArray(value)) {
                        for (const tag of value) {
                            if (typeof tag !== 'string' || tag.length > 50) {
                                return 'Each tag must be a string with maximum 50 characters';
                            }
                        }
                    }
                    return true;
                }
            },
            images: {
                required: false,
                type: 'array',
                custom: (value) => {
                    if (value && Array.isArray(value)) {
                        for (const image of value) {
                            if (typeof image !== 'string' || !this.isValidUrl(image)) {
                                return 'Each image must be a valid URL';
                            }
                        }
                    }
                    return true;
                }
            },
            status: {
                required: false,
                type: 'string',
                enum: ['active', 'inactive', 'discontinued', 'out_of_stock']
            },
            is_featured: {
                required: false,
                type: 'boolean'
            },
            discount_percentage: {
                required: false,
                type: 'number',
                min: 0,
                max: 100
            },
            meta_title: {
                required: false,
                type: 'string',
                maxLength: 60
            },
            meta_description: {
                required: false,
                type: 'string',
                maxLength: 160
            }
        };

        // 库存更新验证规则
        this.stockUpdateRules = {
            stock_quantity: {
                required: true,
                type: 'integer',
                min: 0
            },
            operation: {
                required: false,
                type: 'string',
                enum: ['set', 'add', 'subtract'],
                default: 'set'
            }
        };

        // 价格更新验证规则
        this.priceUpdateRules = {
            price: {
                required: true,
                type: 'number',
                min: 0,
                custom: (value) => {
                    if (value !== undefined && value !== null) {
                        const decimalPlaces = (value.toString().split('.')[1] || '').length;
                        if (decimalPlaces > 2) {
                            return 'Price cannot have more than 2 decimal places';
                        }
                    }
                    return true;
                }
            },
            discount_percentage: {
                required: false,
                type: 'number',
                min: 0,
                max: 100
            }
        };

        // 数据转换规则
        this.transformRules = {
            name: 'trim',
            description: 'trim',
            category: 'trim',
            brand: 'trim',
            sku: (value) => value ? value.trim().toUpperCase() : value,
            price: 'number',
            stock_quantity: 'number',
            weight: 'number',
            status: 'lowercase',
            is_featured: 'boolean',
            discount_percentage: 'number',
            meta_title: 'trim',
            meta_description: 'trim',
            tags: (value) => {
                if (Array.isArray(value)) {
                    return value.map(tag => typeof tag === 'string' ? tag.trim().toLowerCase() : tag);
                }
                return value;
            }
        };
    }

    /**
     * 验证URL格式
     * @param {string} url - 要验证的URL
     * @returns {boolean}
     */
    isValidUrl(url) {
        try {
            new URL(url);
            return true;
        } catch {
            return false;
        }
    }

    /**
     * 验证产品创建数据
     * @returns {Object} - 验证结果
     */
    validateForCreate() {
        this.setValidationRules(this.createRules);
        this.setTransformRules(this.transformRules);
        return this.validateAndTransform();
    }

    /**
     * 验证产品更新数据
     * @returns {Object} - 验证结果
     */
    validateForUpdate() {
        this.setValidationRules(this.updateRules);
        this.setTransformRules(this.transformRules);
        return this.validateAndTransform();
    }

    /**
     * 验证库存更新数据
     * @returns {Object} - 验证结果
     */
    validateForStockUpdate() {
        this.setValidationRules(this.stockUpdateRules);
        this.setTransformRules({
            stock_quantity: 'number',
            operation: 'lowercase'
        });
        return this.validateAndTransform();
    }

    /**
     * 验证价格更新数据
     * @returns {Object} - 验证结果
     */
    validateForPriceUpdate() {
        this.setValidationRules(this.priceUpdateRules);
        this.setTransformRules({
            price: 'number',
            discount_percentage: 'number'
        });
        return this.validateAndTransform();
    }

    /**
     * 计算折扣后价格
     * @returns {number|null} - 折扣后价格
     */
    getDiscountedPrice() {
        const price = this.data.price;
        const discount = this.data.discount_percentage;
        
        if (price && discount && discount > 0) {
            return parseFloat((price * (1 - discount / 100)).toFixed(2));
        }
        
        return price || null;
    }

    /**
     * 获取产品搜索关键词
     * @returns {Array} - 搜索关键词数组
     */
    getSearchKeywords() {
        const keywords = [];
        
        if (this.data.name) {
            keywords.push(...this.data.name.toLowerCase().split(' '));
        }
        
        if (this.data.category) {
            keywords.push(this.data.category.toLowerCase());
        }
        
        if (this.data.brand) {
            keywords.push(this.data.brand.toLowerCase());
        }
        
        if (this.data.tags && Array.isArray(this.data.tags)) {
            keywords.push(...this.data.tags.map(tag => tag.toLowerCase()));
        }
        
        // 去重并过滤空值
        return [...new Set(keywords.filter(keyword => keyword && keyword.length > 0))];
    }

    /**
     * 获取用于API响应的公开数据
     * @returns {Object} - 公开的数据对象
     */
    getPublicData() {
        const publicData = this.getCleanData();
        
        // 添加计算字段
        if (publicData.price && publicData.discount_percentage) {
            publicData.discounted_price = this.getDiscountedPrice();
        }
        
        // 添加搜索关键词
        publicData.search_keywords = this.getSearchKeywords();
        
        return publicData;
    }

    /**
     * 获取用于搜索索引的数据
     * @returns {Object} - 搜索索引数据
     */
    getSearchIndexData() {
        return {
            id: this.data.id,
            name: this.data.name,
            description: this.data.description,
            category: this.data.category,
            brand: this.data.brand,
            tags: this.data.tags || [],
            keywords: this.getSearchKeywords(),
            price: this.data.price,
            discounted_price: this.getDiscountedPrice(),
            status: this.data.status,
            is_featured: this.data.is_featured
        };
    }

    /**
     * 静态方法：验证产品创建数据
     * @param {Object} data - 产品数据
     * @returns {Object} - 验证结果
     */
    static validateCreate(data) {
        const dto = new ProductDTO(data);
        return dto.validateForCreate();
    }

    /**
     * 静态方法：验证产品更新数据
     * @param {Object} data - 产品数据
     * @returns {Object} - 验证结果
     */
    static validateUpdate(data) {
        const dto = new ProductDTO(data);
        return dto.validateForUpdate();
    }

    /**
     * 静态方法：验证库存更新数据
     * @param {Object} data - 库存数据
     * @returns {Object} - 验证结果
     */
    static validateStockUpdate(data) {
        const dto = new ProductDTO(data);
        return dto.validateForStockUpdate();
    }

    /**
     * 静态方法：验证价格更新数据
     * @param {Object} data - 价格数据
     * @returns {Object} - 验证结果
     */
    static validatePriceUpdate(data) {
        const dto = new ProductDTO(data);
        return dto.validateForPriceUpdate();
    }
}

export default ProductDTO;
